package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Override
    public void cutStock(Map<Long,Integer> map) {
        Set<Long> keySet = map.keySet();
        for (Long key : keySet) {
            Sku sku = getById(key);
            Integer decrement = map.get(key);
            Integer stock = sku.getStock();
            if (decrement <= stock){
                sku.setStock(stock-decrement);
            }else {
                sku.setStock(0);
            }
            updateById(sku);
        }
    }
    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStocks";
    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
//        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
//            Long skuId = entry.getKey();
//            Integer num = entry.getValue();
//            Sku sku = getById(skuId);
//            if (sku.getStock() < num)
//                throw new LyException(400,"库存不足");
//            HashMap<String, Object> param = new HashMap<>();
//            param.put("id",skuId);
//            param.put("num",num);
//            getBaseMapper().deductStock(param);
//        }
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                HashMap<String, Object> param = new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
                sqlSession.update(DEDUCT_STOCK_STATEMENT,param);
            }
            sqlSession.flushStatements();
        });
    }

    @Override
    public Sku getBySkuId(Long id) {
        Sku sku = getById(id);
        return sku;
    }

    private static final String ADD_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.addStock";
    @Override
    @Transactional
    public void plusStock(Map<Long, Integer> cartMap) {
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                Map<String, Object> param = new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
                sqlSession.update(ADD_STOCK_STATEMENT,param);
                sqlSession.flushStatements();
            }
        });
    }
}
